package com.example.activemq.config;

import com.example.util.common.StringCommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.rmi.UnknownHostException;
import java.util.Optional;

/**
 * @author LiYuhang
 * @version 0.1
 * @application  服务信息
 * @Date 2021/1/9 20:07
 */
@Component
public class MyApplicationConfig implements ApplicationListener<WebServerInitializedEvent> {

    private static final Logger logger = LoggerFactory.getLogger(MyApplicationConfig.class);

    public static String ip;
    public static String serverPort;
    public static String ipServerPort;
    public static String active;
    public static String contextPath;

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        try {
            Environment env = event.getApplicationContext().getEnvironment();
            ip = StringCommonUtils.getLocalHostLANAddress().getHostAddress();
            serverPort = Optional.ofNullable(env.getProperty("server.port")).orElse("8080");
            active = Optional.ofNullable(env.getProperty("spring.profiles.active")).orElse("");
            contextPath = Optional.ofNullable(env.getProperty("server.servlet.context-path")).orElse("");
            ipServerPort = ip + ":" + serverPort;

        } catch (UnknownHostException e) {
            e.printStackTrace();
            logger.info("获取IP地址失败{},{}",e.getMessage(),e.getCause(),e);
        }
    }

    /**
     * 打印服务器信息
     * @param logger
     */
    public static void printServerInfo(Logger logger) {
        logger.info("\n\t----------------------------------------------------------\n\t" +
                "SpringBoot web " + active + " Start Success \n\t" +
                "Application is Running! Access URLs:\n\t" +
                "Local: \t\thttp://localhost:" + serverPort + contextPath + "/\n\t" +
                "External: \thttp://" + ip + ":" + serverPort + contextPath + "/\n\t" +
                "swagger2: \thttp://" + ip + ":" + serverPort + contextPath + "/doc.html\n\t" +
                "----------------------------------------------------------");
    }

}
